package com.scau.clothes.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {
    private static final String SECRET = "51#Sj2#*(nvf^da_+=>,2W|:'$&dfkj123)";

    /**
     * 生成token
     * @param info
     * @return
     */
    public static String createToken(Map<String,String> info){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,24);
        JWTCreator.Builder builder = JWT.create();
        info.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验证token 验证失败会出异常
     * @param token
     */
    public static DecodedJWT verify(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decRes = verifier.verify(token);
        return decRes;
    }

}
